<template>
  <!-- 新增修改推窗 -->
  <BaseDrawer
    width="50%"
    :title="drawerTitle"
    placement="right"
    v-model:visible="open"
    :maskClosable="false"
    @close="handleClose"
  >
    <template #default>
      <a-form
        v-if="open"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item :label="t('routes.dict.dictName')" name="dictType">
              <a-input
                disabled
                v-model:value="formState.dictType"
                :placeholder="t('routes.dict.dictTypePlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dict.dictLabel')" name="dictLabel">
              <a-input
                v-model:value="formState.dictLabel"
                :placeholder="t('routes.dict.dictLabelPlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dict.dictValue')" name="dictValue">
              <a-input
                v-model:value="formState.dictValue"
                :placeholder="t('routes.dict.dictValuePlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dict.dictSort')" name="dictSort">
              <a-input-number
                class="!w-[100%]"
                v-model:value="formState.dictSort"
                :placeholder="t('routes.dict.dictSortPlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dict.status')" name="status">
              <a-radio-group
                v-model:value="formState.status"
                :options="disableOptions"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.dict.remark')" name="remark">
              <a-textarea
                :rows="3"
                v-model:value="formState.remark"
                :placeholder="t('routes.dict.remarkPlaceholder')"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <template #footer>
      <a-button type="primary" class="mr-3" @click="handleSubmit">
        {{ t("common.okText") }}
      </a-button>
      <a-button @click="handleClose">{{ t("common.cancelText") }}</a-button>
    </template>
  </BaseDrawer>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, onMounted, nextTick } from "vue";
import {
  Row,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  RadioGroup,
  Textarea,
} from "ant-design-vue";
import BaseDrawer from "@/components/BaseDrawer/index.vue";
import { listType } from "@/api/admin/system/dict/type";
import { getDataById, addData, updateData } from "@/api/admin/system/dict/data";
import { getDict } from "@/utils/dictFormat";
import useDrawer from "@/hooks/useDrawer";
import { message as Message } from "ant-design-vue";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { IData } from "@/api/admin/system/dict/data/type";
import { useI18n } from "@/hooks/useI18n";

const { t } = useI18n();

interface FormState {
  id: undefined | number;
  dictType: string | undefined;
  dictValue: string;
  dictLabel: string;
  dictSort: number;
  status: string;
  remark: string;
}
export default defineComponent({
  components: {
    "a-row": Row,
    "a-col": Col,
    "a-form": Form,
    "a-form-item": FormItem,
    "a-input": Input,
    "a-input-number": InputNumber,
    "a-radio-group": RadioGroup,
    "a-textarea": Textarea,
    BaseDrawer,
  },
  emits: ["finished"],
  setup(props, { expose, emit }) {
    const typeOptions = ref();
    const disableOptions = ref<IData[]>([]);
    const rules = {
      dictName: [
        {
          required: true,
          message: t("routes.dict.dictNameCannotBeRmpty"),
          trigger: "blur",
        },
      ],
      dictLabel: [
        {
          required: true,
          message: t("routes.dict.dictTypeCannotBeRmpty"),
          trigger: "blur",
        },
      ],
      status: [
        {
          required: true,
          message: t("routes.dict.状态不能为空"),
          trigger: "change",
        },
      ],
    };

    const formRef = ref();
    const formState: FormState = reactive({
      id: undefined,
      dictType: "",
      dictLabel: "",
      dictValue: "",
      dictSort: 1,
      status: "1",
      remark: "",
    });
    const { open, drawerTitle, handleOpenDrawer, handleCloseDrawer } =
      useDrawer();
    // 隐藏推窗
    const handleClose = (cb?: () => void) => {
      handleCloseDrawer.value(() => {
        formState.id = undefined;
        formRef.value.resetFields();
        cb && typeof cb === "function" && cb();
      });
    };
    // 显示推窗
    const handleShow = (dictType: string, row?: IData) => {
      handleOpenDrawer.value(() => {
        if (row && row.id) {
          drawerTitle.value = t("common.update");
          getDataById(row.id).then((res) => {
            formState.dictType = dictType;
            nextTick(() => {
              Object.keys(formState).forEach((key) => {
                formState[key] = res.data[key];
              });
            });
          });
        } else {
          drawerTitle.value = t("common.add");
          formState.dictType = dictType;
        }
      });
    };
    // 表单提交
    const handleSubmit = () => {
      console.log(formState);
      formRef.value
        .validate()
        .then(() => {
          if (formState.id) {
            updateData(formState).then((res) => {
              handleClose(() => {
                Message.success(res.message);
                emit("finished");
              });
            });
          } else {
            addData(formState).then((res) => {
              handleClose(() => {
                Message.success(res.message);
                emit("finished");
              });
            });
          }
        })
        .catch((error: ValidateErrorEntity) => {
          console.log("error", error);
        });
    };

    onMounted(async () => {
      disableOptions.value = await getDict("sys_normal_disable");
      disableOptions.value.forEach((item) => {
        item.label = item.dictLabel;
        item.value = item.dictValue;
      });
      listType().then((res) => {
        typeOptions.value = res.data.rows;
      });
    });

    expose({
      handleShow,
    });

    return {
      t,
      open,
      drawerTitle,
      formState,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      rules,
      formRef,
      handleClose,
      handleSubmit,
      confirm,
      disableOptions,
    };
  },
});
</script>
